package com.ruoyi.DingDing.Domain;

import ch.qos.logback.classic.Logger;
import com.aliyun.tea.*;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.taobao.api.ApiException;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@RestController     //声明spring组件也可以使用 @component
public class DingDingText {
    @Resource
    private ISysUserService sysUserService; //正常引用service

    private static DingDingText dingDingText;   //将自己作为静态私有变量引入。使其在springmvc初始化前就被创建

    @PostConstruct      // 通过@PostConstruct 和 @PreDestroy 方法实现初始化和销毁bean之前进行的操作
    public void init(){
        dingDingText = this;
        dingDingText.sysUserService = this.sysUserService;  // 初始化时将已静态化的Service实例化
    }

     public static Logger log ;


    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     * CorpId: ding02f07d3b9078326dacaaa37764f94726
     * AgentId: 2478286144
     * AppKey: dinguz8ebdfa6kif1kz8
     * AppSecret: DRTOkf44KDkvu3FGVZI1-dLFYqZ-Una6_v1x0hQIjJxh98cpD_R5NKisJKNA-2Yb
     */
    private static String AppKey = "dinguz8ebdfa6kif1kz8";
    private static String AppSecret = "DRTOkf44KDkvu3FGVZI1-dLFYqZ-Una6_v1x0hQIjJxh98cpD_R5NKisJKNA-2Yb";
    private static String CorpId = "ding02f07d3b9078326dacaaa37764f94726";
    private  static String AgentId = "2478286144";
    public static com.aliyun.dingtalkrobot_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkrobot_1_0.Client(config);
    }

    /**
     * 获取企业accessToken
     * @return
     */
    public static String getToken(){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(AppKey);
            req.setAppsecret(AppSecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            System.out.println(rsp.getBody());
            return rsp.getAccessToken();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过手机号获取userId
     * @param accessToken
     * @param mobile
     * @return
     */
    public static String getUserId(String accessToken,String mobile){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
            return rsp.getResult().getUserid();
        } catch (ApiException e) {
//            e.printStackTrace();
            log.error(mobile+"手机号找不到对应角色",e);
        }
        return null;
    }
    /**
     * 通过角色找到对应所有用户的手机号
     * @param currentApprover
     * @return
     */
    public List<String> getUserIdsByRoleId(String accessToken,Long currentApprover){
        List <String> userIds = new ArrayList<>();
        List<SysUserRole> users = dingDingText.sysUserService.selectUserIdByRoleId(currentApprover);
        for(SysUserRole s : users){
            try {
                Long userId = s.getUserId();
                if(!dingDingText.sysUserService.selectUserById(userId).getPhonenumber().equals("")){    // 使用dingDingText.sysUserService的方式使用service
                    if(!getUserId(accessToken,dingDingText.sysUserService.selectUserById(userId).getPhonenumber()).isEmpty()){
                        userIds.add(getUserId(accessToken,dingDingText.sysUserService.selectUserById(userId).getPhonenumber()));
                    }
                }
            }catch (Exception e){
                System.out.println("手机号找不到对应角色");
            }
        }
        return userIds;
    }
    public void BatchRobotText(Long currentApprover) throws Exception {
        String accessToken = getToken();
        List<String>userIds = getUserIdsByRoleId(accessToken,currentApprover);
//        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkrobot_1_0.Client client = DingDingText.createClient();
        com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders batchSendOTOHeaders = new com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = accessToken;
        com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest batchSendOTORequest = new com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest()
                .setMsgParam("{      \"title\": \"待审批\",      \"text\": \"您有一条新的待审批事项\",      \"singleTitle\": \"查看详情\",      \"singleURL\": \"http://122.226.244.182:8081\" }")
                .setMsgKey("sampleActionCard")
                .setRobotCode("dinguz8ebdfa6kif1kz8")
                .setUserIds(userIds);
        try {
            client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
    }

}